package com.cqupt.service.impl;

import com.cqupt.mapper.EnclosureMapper;
import com.cqupt.pojo.Enclosure;
import com.cqupt.service.FileManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class FileManagerServiceImpl implements FileManagerService {

    @Autowired
    private EnclosureMapper enclosureMapper;


    /**
     * 上传附件
     * @param files 附件（支持多个附件）
     * @param id 知识id
     * @param sumbit_user 提交者
     * @param submit_time 提交时间
     * @return
     */
    @Override
    public boolean uploadFiles(MultipartFile[] files,int id, String sumbit_user, String submit_time)  {

            // 获取当前时间
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSS");
            String res = sdf.format(new Date());
            // 上传位置（自定义上传位置，可修改）
            String rootPath = "D:/DevOpsProject/upload";
            try {
                // 遍历每个文件
                for (int i = 0; i < files.length; i++) {
                    MultipartFile file = files[i];
                    // 原始名称
                    String originalFileName = file.getOriginalFilename();
                    // 新文件名
                    String newFileName = res +"_"+ originalFileName;
                    // 创建用户名/年/月文件夹
                    Calendar date = Calendar.getInstance();
                    File dateDirs = new File(id + File.separator + date.get(Calendar.YEAR) + File.separator + (date.get(Calendar.MONTH) + 1));
                    // 新文件
                    File newFile = new File(rootPath + File.separator + dateDirs + File.separator + newFileName);
                    if (!newFile.getParentFile().exists()) {
                        // 如果目标文件所在的目录不存在，则创建父目录
                        newFile.getParentFile().mkdirs();
                    }
                    // 将内存中的数据写入磁盘
                    file.transferTo(newFile);
                    Enclosure enclosure = new Enclosure(newFile.toString(), id, sumbit_user,submit_time);
                    // 附件信息插入数据库总
                    Integer flag = enclosureMapper.insertEnclosure(enclosure);
                    if (flag != 1) {
                        return false;
                    }
                }
                return true;
            }catch (Exception e) {
                return false;
            }
    }

    /**
     * 知识上传
     * @param files 附件列表
     * @param id 知识id
     * @param closureIds 附件id
     * @param submit_user 提交者
     * @param submit_time
     * @return
     */
    @Override
    public boolean updateFiles(MultipartFile[] files, int id, String[] closureIds, String submit_user,String submit_time) {

        // 先过滤未修改动的id，若id不变则不修改其附件
        Map<String, Object> params = new HashMap<>();
        params.put("id", id);
        params.put("closureIds",closureIds);
        // 插入额外增加的附件
        Integer flagDelete = enclosureMapper.deleteRedudentEnclosureByid(params);
        if (flagDelete < 0) {
            return false;
        }
        // 获取当前时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSS");
        String res = sdf.format(new Date());
        // 上传位置（可修改）
        String rootPath = "D:/DevOpsProject/upload";
        try {
            // 遍历额外更新的附件列表
            for (int i = 0; i < files.length; i++) {
                MultipartFile file = files[i];
                // 原始名称
                String originalFileName = file.getOriginalFilename();
                // 新文件名
                String newFileName = res +"_"+ originalFileName;
                // 创建用户名/年/月文件夹
                Calendar date = Calendar.getInstance();
                File dateDirs = new File(id + File.separator + date.get(Calendar.YEAR) + File.separator + (date.get(Calendar.MONTH) + 1));
                // 新文件
                File newFile = new File(rootPath + File.separator + dateDirs + File.separator + newFileName);
                if (!newFile.getParentFile().exists()) {
                    // 如果目标文件所在的目录不存在，则创建父目录
                    newFile.getParentFile().mkdirs();
                }
                // 将内存中的数据写入磁盘
                file.transferTo(newFile);
                Enclosure enclosure = new Enclosure(newFile.toString(), id,submit_user,submit_time);
                Integer flagInsert = enclosureMapper.insertEnclosure(enclosure);
                if (flagInsert != 1) {
                    return false;
                }
            }
            return true;
        }catch (Exception e) {
            return false;
        }
    }

    /**
     * 删除附件
     * @param id 知识id
     * @return
     */
    @Override
    public boolean deleteFiles(int id) {
        int flag = enclosureMapper.deleteEnclosureByid(id);
        if (flag < 0) {
            return false;
        }else{
            return true;
        }
    }

    /**
     * 下载附件
     * @param filedir 附件地址
     * @param request 请求
     * @param response
     * @return
     */
    public boolean downloadFile(String filedir, HttpServletRequest request, HttpServletResponse response){

        try {
            //转码，免得文件名中文乱码(有时候加上反而会乱码)
            // fileName = URLEncoder.encode(fileName,"UTF-8");
            //从路径中获取文件名称，trim：去除字符串前后的空格
            File tempFile = new File(filedir);
            String filename = tempFile.getName();
            //System.out.println("filename:"+filename);
            //解决中文文件名乱码
            String userAgent = request.getHeader("User-Agent");
            //IE内核浏览器
            if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
                filename = java.net.URLEncoder.encode(filename, "UTF-8");
            } else {
                // 非IE浏览器的处理：
                filename = new String(filename.getBytes("UTF-8"), "ISO-8859-1");
            }
            //设置文件下载头
            response.setHeader("Content-disposition",String.format("attachment; filename=\"%s\"", filename));
            //设置文件ContentType类型，这样设置，会自动判断下载文件类型
            response.setContentType("multipart/form-data");
            response.setCharacterEncoding("UTF-8");
            InputStream inputStream = new BufferedInputStream(new FileInputStream(new File(filedir)));
            BufferedOutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            //创建缓冲区
            byte[] buffer = new byte[1024];
            int length;
            while ((length = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, length);
                outputStream.flush();
            }
            //关闭流
            inputStream.close();
            outputStream.close();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 根据id获取附件
     * @param id 知识id
     * @return
     */
    @Override
    public List<Map<String, Object>> getClosuresByID(int id) {
        return enclosureMapper.getEnclosureById(id);
    }


}
